package com.hontech.bv.http

import com.hontech.bv.utils.parseJson
import kotlinx.coroutines.CompletableDeferred
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException



class RespCallback(private val promise: CompletableDeferred<ByteArray>) : Callback {

    override fun onFailure(call: Call, e: IOException) {
        promise.completeExceptionally(e)
    }

    private fun parseResp(response: Response) {
        val statusCode = response.code
        if (statusCode != 200) {
            throw IOException("响应头错误:$statusCode")
        }

        val body = response.body ?: throw IOException("没有响应内容")

        val buf = body.bytes()

        val head = response.header(Http.HEAD_RESP, Http.RESP_FAIL)

        if ((head == null) || (head == Http.RESP_FAIL)) {
            val errResp = parseJson<ErrResp>(buf)
            throw IOException(errResp.errMsg)
        }

        promise.complete(buf)
    }

    override fun onResponse(call: Call, response: Response) {
        try {
            parseResp(response)
        } catch (e: Exception) {
            promise.completeExceptionally(e)
        }
    }
}
